package com.company.dcm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.dcm.common.R;
import com.company.dcm.entity.R_ClothSheetDetailFourScore;
import com.company.dcm.entity.R_ClothSheetFourScore;
import com.company.dcm.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 王泽同
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/ClothSheetFourScore")
public class ClothSheetFourScoreController {
    @Value("${dcm.image-prefix}")
    private String prefix;
    
    @Autowired
    ResourceLoader resourceLoader;
    @Autowired
    private R_ClothSheetFourScoreService rClothSheetFourScoreService;
    @Autowired
    private R_ClothSheetDetailFourScoreService rClothSheetDetailFourScoreService;
    
    @Autowired
    private R_ClothSheetDtoService r_clothSheetDtoService;
    @Autowired
    private R_ClothSheetDetailService r_clothSheetDetailService;
    @Autowired
    private DevService devService;

    @GetMapping("/download/R_ClothSheetDetailFourScore")
    public void downloadR_ClothSheetFourScore(HttpServletResponse response,String serialno,String deviceCode) throws IOException {
        if(StringUtils.isAnyBlank(serialno,deviceCode)){
            Map<String, String> map = MapUtils.newHashMap();
            map.put("code", "0");
            map.put("data", "参数不能为空！");
            response.getWriter().println(JSON.toJSONString(map));
            return;
        }

        List<R_ClothSheetDetailFourScore> list = null;
        list = rClothSheetDetailFourScoreService.list(new LambdaQueryWrapper<R_ClothSheetDetailFourScore>()
                .eq(R_ClothSheetDetailFourScore::getDeviceCode,deviceCode)
                .eq(R_ClothSheetDetailFourScore::getSerialno,serialno));

        if(list==null|list.size()==0){
            R_ClothSheetDetailFourScore r_clothSheetDetailFourScore = new R_ClothSheetDetailFourScore();
            r_clothSheetDetailFourScore.setRecord("暂无相关数据！");
            list.add(r_clothSheetDetailFourScore);
//            Map<String, String> map = MapUtils.newHashMap();
//            map.put("code", "0");
//            map.put("data", "查询结果为空！");
//            response.getWriter().println(JSON.toJSONString(map));
//            return;
        }

        int i=1;
        for(R_ClothSheetDetailFourScore r : list){
            r.setNo(i++);
        }

//        R_ClothSheetFourScore r_clothSheetFourScore = rClothSheetFourScoreService.getOne(new LambdaQueryWrapper<R_ClothSheetFourScore>()
//                .eq(R_ClothSheetFourScore::getDeviceCode,deviceCode)
//                .eq(R_ClothSheetFourScore::getSerialNo,serialno));
//
//        if(r_clothSheetFourScore == null){
//            Map<String, String> map = MapUtils.newHashMap();
//            map.put("code", "0");
//            map.put("data", "查询结果为空！");
//            response.getWriter().println(JSON.toJSONString(map));
//        }

        try {
            // 定义模板文件路径
            ClassPathResource classPathResource = new ClassPathResource("templates"+ File.separator+"报表模版.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            //生成目标文件
            File somethingFile = File.createTempFile("template_export_copy", ".xlsx");
            try {
                FileUtils.copyInputStreamToFile(inputStream, somethingFile);
            } finally {
                IOUtils.close(inputStream);
            }

            // 创建输出流
            ServletOutputStream outputStream = response.getOutputStream();

            // 写入Excel的响应头信息
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "serialno_record.xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);

            // 使用EasyExcel加载模板文件，并填充数据
            EasyExcel.write(outputStream, R_ClothSheetDetailFourScore.class)
                    .withTemplate(somethingFile)
                    .sheet()
                    .doFill(list);

            somethingFile.deleteOnExit();
            // 刷新输出流，确保所有数据都写入
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("/download/R_ClothSheetFourScore error");
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("code", "0");
            map.put("data", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @GetMapping("/search")
    public R<Page<R_ClothSheetFourScore>> search(@RequestParam(name = "pageCurrent", required = false, defaultValue = "1") Integer pageCurrent,
                                  @RequestParam(name = "pageSize", required = false, defaultValue = "3") Integer pageSize,
                                  String deviceCode, 
                                  String checkStartDate, String checkEndDate,
                                  Long factoryId, Long id) {
        List<R_ClothSheetFourScore> result;

        LambdaQueryWrapper<R_ClothSheetFourScore> queryWrapper = new LambdaQueryWrapper<>();
        Page<R_ClothSheetFourScore> page = new Page<>(pageCurrent, pageSize);

        boolean timeFlag = true;

        //1.查出符合的缺陷表（组织sql）
        //1.2按机台设备编号查询
        if (!com.company.dcm.utils.StringUtils.isNullOrEmpty(deviceCode)) {
            queryWrapper.eq(R_ClothSheetFourScore::getDeviceCode, deviceCode);
        }
        //1.3按车间查询
        else if(id!=null){
            List<String> deviceCodes = devService.getDeviceCodeByWorkShopId(id);
            if(deviceCodes!=null&&deviceCodes.size()>0){
                queryWrapper.in(R_ClothSheetFourScore::getDeviceCode, deviceCodes);
            }else {
                timeFlag =false;
            }
        }
        //1.4按厂房查询
        else if(factoryId!=null){
            List<String> deviceCodes = devService.getDeviceCodeByFactoryId(factoryId);
            if(deviceCodes!=null&&deviceCodes.size()>0){
                queryWrapper.in(R_ClothSheetFourScore::getDeviceCode, deviceCodes);
            }
            else {
                timeFlag =false;
            }
        }

        //1.5都没有，按当前权限返回
//        if(factoryId==null&id==null&StringUtils.isNullOrEmpty(deviceCode)&StringUtils.isNullOrEmpty(clothCode)){
        else {
            List<String> deviceCodes = devService.getDeviceCodeByAuth();
            if(deviceCodes!=null&&deviceCodes.size()>0) {
                queryWrapper.in(R_ClothSheetFourScore::getDeviceCode, deviceCodes);
            }
            else {
                timeFlag =false;
            }
        }


        //1.6按检测时间查询，查询当天的记录
        if(timeFlag){
            if((!com.company.dcm.utils.StringUtils.isNullOrEmpty(checkStartDate))&&(!com.company.dcm.utils.StringUtils.isNullOrEmpty(checkEndDate))) {
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date checkStartDateTurn = ft.parse(checkStartDate);
                    Date checkEndDateTurn = ft.parse(checkEndDate);
                    queryWrapper.between(R_ClothSheetFourScore::getCheckDate, checkStartDateTurn, checkEndDateTurn);
                } catch (ParseException e) {
                    return R.error("日期格式不对!");
                }
            }
            //2.按时间倒序查询缺陷表分页
            queryWrapper.orderByDesc(R_ClothSheetFourScore::getCheckDate);
            Page<R_ClothSheetFourScore> rClothSheetFourScorePage = rClothSheetFourScoreService.page(page, queryWrapper);
            result = rClothSheetFourScorePage.getRecords();

            for (R_ClothSheetFourScore r:result) {
                r.setHasDetails
                        (rClothSheetDetailFourScoreService.count(new LambdaQueryWrapper<R_ClothSheetDetailFourScore>()
                        .eq(R_ClothSheetDetailFourScore::getDeviceCode, r.getDeviceCode())
                        .eq(R_ClothSheetDetailFourScore::getSerialno, r.getSerialNo())) > 0);
            }

            Page<R_ClothSheetFourScore> pageResult = new Page<>();
            pageResult.setRecords(result);
            pageResult.setCurrent(rClothSheetFourScorePage.getCurrent());
            pageResult.setSize(rClothSheetFourScorePage.getSize());
            pageResult.setTotal(rClothSheetFourScorePage.getTotal());

            return R.success(pageResult);
        }
        return R.success(null);
    }

}
